#!usr/bin/python
# -*- coding: UTF-8 -*-
# @Time    : 2025/9/18 11:56
# @Author  : 2019102
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5


class UserNameRsaEncode:
    @classmethod
    def username_rsa_encode(cls, username):
        """用户名rsa公钥加密+base64处理"""
        pubkey = """-----BEGIN PUBLIC KEY-----\n
            MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkCKw/9/dE/3qNauM2YoXoePOPr6nxwt8RAM0bEI4kN1xOJKqZy9gpCLH9dmZMqVN2Rc5hc7ecoERf6xp1IODLVZgj4tFXnFW17KmXIglTM+JtabwTiu1y28pXhDwWR0avBlJEQHISmXCkIHVfB3FWYk8z4uR147yNxv7akS8a7wIDAQAB
            -----END PUBLIC KEY-----"""
        rsa_encode_result, err = cls.rsa_encrypt(username.encode(), pubkey)
        if err is not None:
            print("RSA encode fail:", err)
            return ""
        username_byte = cls.base64_encode(rsa_encode_result)
        return username_byte.decode()

    @classmethod
    def rsa_encrypt(cls, username_bytes, pubkey):
        orig_data = username_bytes
        key = RSA.importKey(pubkey)
        cipher = PKCS1_v1_5.new(key)
        crt_data = cipher.encrypt(orig_data)
        return crt_data, None

    @classmethod
    def base64_encode(cls, raw):
        encoded = base64.standard_b64encode(raw)
        return encoded


if __name__ == '__main__':
    print(UserNameRsaEncode.username_rsa_encode("admin"))